//
//  JWYHGRinfoVC.m
//  test
//
//  Created by 李彦宏 on 2018/3/7.
//  Copyright © 2018年 朱圳. All rights reserved.
//

#import "JWYHGRinfoVC.h"
#import "JWUserManager.h"
#import "JWGRUsermodel.h"
#import "GraduateCellTableViewCell.h"//详情cell
#import "UITextField+Limit.h"
#import "BRPickerView.h"


#define GraduateCellTableViewCellID @"GraduateCellTableViewCell"
@interface JWYHGRinfoVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate>


@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) JWGRUsermodel *model;
@property(nonatomic,strong)NSMutableArray *CellContent;//cell内容
@property (nonatomic, strong) UIButton *rightBtnitem;


@end

@implementation JWYHGRinfoVC

//UItableView初始化
- (void)setupTable
{
    UITableView *tableView=[[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    //隐藏组距导航栏的间距
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    tableView.backgroundColor=[UIColor whiteColor];
    tableView.showsHorizontalScrollIndicator=NO;
    tableView.showsVerticalScrollIndicator=NO;
    tableView.dataSource=self;
    tableView.delegate=self;
    tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:tableView];
    self.tableView=tableView;
    
    [tableView registerNib:[UINib nibWithNibName:@"GraduateCellTableViewCell" bundle:nil] forCellReuseIdentifier:GraduateCellTableViewCellID];
    //    [tableView registerNib:[UINib nibWithNibName:@"HomeNearbyShopView" bundle:nil] forHeaderFooterViewReuseIdentifier:HomeNearbyShopViewID];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.model=[JWUserManager Gme];
    [self setupTable];
    _CellContent=[NSMutableArray arrayWithObjects:@"姓名：",@"电话：", @"届数：",@"院校专业：",@"地址：",@"打款方式：",@"打款帐号：",@"成绩：",@"备注：",nil];
    
    
    //rightNavBtn
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;
    [rightBtn setFrame:CGRectMake(0, 0, 44, 44)];
    [rightBtn setTitle:@"修改" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    self.rightBtnitem=rightBtn;
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:16];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
}
-(void)rightBtnClick:(UIButton *)send{
    if([send.titleLabel.text isEqualToString:@"修改"]){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            
        });
        [send setTitle:@"保存" forState:UIControlStateNormal];
        send.titleLabel.font=[UIFont systemFontOfSize:20];
        [send setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }else{
        if(self.model.beizhu==nil){
            self.model.beizhu=@" ";
        }else if (self.model.achievement==nil){
            self.model.achievement=@" ";
        }else if (self.model.college==nil){
            self.model.college=@" ";
        }else if (self.model.address==nil){
            self.model.address=@" ";
        }else if (self.model.jieshu==nil){
            self.model.jieshu=@" ";
        }else if (self.model.moneyway==nil){
            self.model.moneyway=@" ";
        }else if (self.model.moneynumber==nil){
            self.model.moneynumber=@" ";
        }
        
        BOOL isTel = [self validateMobile:self.model.phone];
        if (isTel == YES ) {
            if (self.model.ID==nil) {
                self.model.ID = self.model.gid;
            }
            NSDictionary *dict=@{
                                 @"jwid" : JWid,
                                 @"jwpassword" :JWpassword,
                                 @"gid": self.model.ID,
                                 @"name":self.model.name,
                                 @"jieshu":self.model.jieshu,
                                 @"phone":self.model.phone,
                                 @"college":self.model.college,
                                 @"address":self.model.address,
                                 @"moneyway":self.model.moneyway,
                                 @"moneynumber":self.model.moneynumber,
                                 @"achievement":self.model.achievement,
                                 @"beizhu":self.model.beizhu,
                                 };
            NSLog(@"--dict>>--%@", dict);
            [[AFNetworkTool shareManager]postJSONWithUrl:Grduat_update parmas:dict successData:^(id json) {
      //          NSLog(@"-json-%@",json);
                
                if ([json[@"message"] isEqualToString:@"修改成功"]) {
                    // 提示
                    self.model=[JWGRUsermodel yy_modelWithJSON:json[@"list"]];
                    [JWUserManager updateGR:self.model];

                    [MBProgressHUD showSuccess:@"修改成功!"];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                    
                }else{
                    [MBProgressHUD showError:@"修改失败！"];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } failure:^(NSError *error) {
                NSLog(@"--error--%@", error);
                [MBProgressHUD showError:@"修改失败"];
            }];
        }else{
            [Utility showFail:@"电话格式不对"];
            
        }
        
    }
}
#pragma -mark -----------------------------tableview datasource and delegate---------------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _CellContent.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row=indexPath.row;
    
    GraduateCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:GraduateCellTableViewCellID];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.GraduateFirstCell.text=_CellContent[indexPath.row];
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImgAction:)];
    tap.numberOfTapsRequired=1;
    tap.numberOfTouchesRequired=1;
    tap.delegate=self;
    
    if([self.rightBtnitem.titleLabel.text isEqualToString: @"修改"]){
        cell.GRtextfiled.enabled=NO;
    }else{
        cell.GRtextfiled.enabled=YES;
       

        cell.GRtextfiled.tag=row;
        cell.GRtextfiled.delegate=self;
        [cell.GRtextfiled addTarget:self action:@selector(GRtfAction:) forControlEvents:UIControlEventEditingChanged];
    }
    
    
    switch (indexPath.row) {
        case 0:
            cell.GRtextfiled.text=self.model.name;
            break;
        case 1:
            cell.GRtextfiled.text=self.model.phone;
            break;
        case 2:
            cell.GRtextfiled.text=self.model.jieshu;
            
            [cell.GRtextfiled addGestureRecognizer:tap];
            break;
        case 3:
            cell.GRtextfiled.text=self.model.college;
            
            break;
        case 4:
            cell.GRtextfiled.text=self.model.address;
            break;
            
        case 5:
            cell.GRtextfiled.text=self.model.moneyway;
            break;
        case 6:
            cell.GRtextfiled.text=self.model.moneynumber;
            break;
        case 7:
            cell.GRtextfiled.text=self.model.achievement;
            break;
        case 8:
            cell.GRtextfiled.text=self.model.beizhu;
            break;
        default:
            break;
    }
    
    return cell;
    
}


#pragma -mark ———————————GRtfAction响应事件—————————————————
-(void)GRtfAction:(UITextField *)Textfield
{
    switch (Textfield.tag) {
        case 0:
            self.model.name=Textfield.text;
            break;
        case 1:
            self.model.phone=Textfield.text;
            [Textfield setLimitTextLength:11];
            break;
        case 2:
//            self.model.jieshu=Textfield.text;
            break;
        case 3:
            self.model.college=Textfield.text;
            break;
        case 4:
            self.model.address=Textfield.text;
            break;
            
        case 5:
            self.model.moneyway=Textfield.text;
            break;
        case 6:
            self.model.moneynumber=Textfield.text;
            break;
        case 7:
            self.model.achievement=Textfield.text;
            break;
        case 8:
            self.model.beizhu=Textfield.text;
            break;
        default:
            break;
    }
}
#pragma -mark —————————————————tap响应事件————————————————————
-(void)tapImgAction:(UITapGestureRecognizer *)send{
    [self.view endEditing:YES];
    __weak typeof(self) weakslf = self;
    [BRStringPickerView showStringPickerWithTitle:@"届数" dataSource:@[@"18", @"19", @"20", @"21", @"22", @"23"] defaultSelValue:@"20" isAutoSelect:YES resultBlock:^(id selectValue) {
        self.model.jieshu = selectValue;
        [weakslf.tableView reloadData];
    }];

    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if([self.rightBtnitem.titleLabel.text isEqualToString: @"修改"]){
        if (indexPath.row == 1) {
            NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@", self.model.phone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}


//判断电话格式
- (BOOL)validateMobile:(NSString *)mobile
{
    // 手机号以13、15、18、17开头，八个 \d 数字字符
    NSString * phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(17[0,0-9]))\\d{8}$";
    NSPredicate * phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
